package com.smartstate.ems.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartstate.ems.dto.PageDTO;
import com.smartstate.ems.entity.Dehumidifier;
import com.smartstate.ems.entity.Equipment;
import com.smartstate.ems.entity.ObjMoudel;
import com.smartstate.ems.mapper.DehumidifierMapper;
import com.smartstate.ems.mapper.EquipmentMapper;
import com.smartstate.ems.mapper.ObjMiddleMapper;
import com.smartstate.ems.mapper.ObjMoudelMapper;
import com.smartstate.ems.service.DehumidifierService;
import com.smartstate.ems.vo.DehumidifierVO;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DehumidifierServiceImpl extends ServiceImpl<DehumidifierMapper, Dehumidifier> implements DehumidifierService {

    @Resource
    private EquipmentMapper equipmentMapper;

    @Resource
    private ObjMiddleMapper objMiddleMapper;

    @Resource
    private ObjMoudelMapper objMoudelMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Page<Dehumidifier> queryAllPageByDTO(PageDTO pageDTO) {
        return null;
    }

    @Override
    public List<DehumidifierVO> dehumidifierTree(Integer deviceType) {
        //key:除湿机房  value:属性值
        HashMap<String, List<DehumidifierVO.DehumidifierParameter>> hashMap = new HashMap<>();
        //找出所有除湿机类型的设备
        List<Equipment> equipmentList = equipmentMapper.selectEquipmentByType(deviceType);
        ArrayList<DehumidifierVO> attributesArrayList = new ArrayList<>();
        equipmentList.stream().forEach(equipment -> {
            //有附加属性
            if (equipment.getAdditionalAttribute() != null && !"".equals(equipment.getAdditionalAttribute())) {
                String additionalAttribute = equipment.getAdditionalAttribute();
                List<DehumidifierVO.AdditionalAttributes> additionalAttributes = JSONArray.parseArray(additionalAttribute, DehumidifierVO.AdditionalAttributes.class);
                //去掉RoomLocation为null的对象
                List<DehumidifierVO.AdditionalAttributes> collect = additionalAttributes.stream().filter(item -> item.getRoomLocation() != null).collect(Collectors.toList());
                if (collect != null && collect.size() > 0) {
                    //有附加属性且有除湿机房的请况
                    DehumidifierVO.AdditionalAttributes attributes = collect.get(0);
                    if (hashMap.containsKey(attributes.getRoomLocation())) {//hashmap中有这个key
                        List<DehumidifierVO.DehumidifierParameter> list = hashMap.get(attributes.roomLocation);
//                        DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
//                        parameter.setDeviceId(equipment.getDeviceId());
                        DehumidifierVO.DehumidifierParameter parameter = getData(equipment);
                        if (attributes.getServiceArea() != null) {
                            parameter.setServiceArea(attributes.getServiceArea());
                        }
                        //TODO Redis中的数据

                        list.add(parameter);
                        hashMap.put(attributes.getRoomLocation(), list);
                    } else {//hashmap中没有这个key
                        DehumidifierVO.DehumidifierParameter parameter = getData(equipment);
//                        DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
//                        parameter.setDeviceId(equipment.getDeviceId());
                        if (parameter != null && attributes.getServiceArea() != null) {
                            parameter.setServiceArea(attributes.getServiceArea());
                        }
                        List<DehumidifierVO.DehumidifierParameter> list = new ArrayList<>();
                        //TODO Redis中的数据

                        list.add(parameter);
                        hashMap.put(attributes.roomLocation, list);
                    }
                } else {//有附加属性但是没有除湿机房的情况
                    //根据设备id查询楼宇名称
                    String objName = getaVoid(equipment);
                    if (objName != null) {
                        if (hashMap.containsKey(objName)) {//hashmap中有这个key
                            List<DehumidifierVO.DehumidifierParameter> list = hashMap.get(objName);
//                            DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
//                            parameter.setDeviceId(equipment.getDeviceId());
                            DehumidifierVO.DehumidifierParameter parameter = getData(equipment);
                            List<DehumidifierVO.AdditionalAttributes> attributes = additionalAttributes.stream().filter(item -> item.getServiceArea() != null).collect(Collectors.toList());
                            if (attributes != null && attributes.get(0).getServiceArea() != null && !"".equals(attributes.get(0).getServiceArea())) {
                                if (parameter != null) {
                                    parameter.setServiceArea(attributes.get(0).getServiceArea());
                                } else {
                                    parameter = new DehumidifierVO.DehumidifierParameter();
                                    parameter.setServiceArea(attributes.get(0).getServiceArea());
                                }
                            }
                            //TODO Redis中的数据

                            list.add(parameter);
                            hashMap.put(objName, list);
                        } else {//hashmap中没有这个key
//                            DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
//                            parameter.setDeviceId(equipment.getDeviceId());
                            DehumidifierVO.DehumidifierParameter parameter = getData(equipment);
                            List<DehumidifierVO.AdditionalAttributes> attributes = additionalAttributes.stream().filter(item -> item.getServiceArea() != null).collect(Collectors.toList());
                            if (attributes != null && attributes.get(0).getServiceArea() != null && !"".equals(attributes.get(0).getServiceArea())) {
                                if (parameter != null) {
                                    parameter.setServiceArea(attributes.get(0).getServiceArea());
                                } else {
                                    parameter = new DehumidifierVO.DehumidifierParameter();
                                    parameter.setServiceArea(attributes.get(0).getServiceArea());
                                }
                            }
                            //TODO Redis中的数据
                            List<DehumidifierVO.DehumidifierParameter> list = new ArrayList<>();

                            list.add(parameter);
                            hashMap.put(objName, list);
                        }
                    }
                }
            } else {
                //没有附加属性
                //根据设备id查询楼宇名称
                String objName = getaVoid(equipment);
                if (objName != null) {
                    if (hashMap.containsKey(objName)) {//hashmap中有这个key
                        List<DehumidifierVO.DehumidifierParameter> list = hashMap.get(objName);
//                        DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
//                        parameter.setDeviceId(equipment.getDeviceId());
                        //TODO Redis中的数据
                        DehumidifierVO.DehumidifierParameter parameter = getData(equipment);
                        if (parameter != null) {
                            list.add(parameter);
                        }
                        hashMap.put(objName, list);
                    } else {//hashmap中没有这个key
//                        DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
//                        parameter.setDeviceId(equipment.getDeviceId());
                        //TODO Redis中的数据
                        DehumidifierVO.DehumidifierParameter parameter = getData(equipment);
                        List<DehumidifierVO.DehumidifierParameter> list = null;
                        if (parameter != null) {
                            list = new ArrayList<>();
                            list.add(parameter);
                        }
                        hashMap.put(objName, list);
                    }
                }
            }

        });
        //获取hashmap中所有的key
        for (String key : hashMap.keySet()) {
            DehumidifierVO dehumidifierVO = new DehumidifierVO();
            dehumidifierVO.setDehumidifierRoom(key);
            dehumidifierVO.setDehumidifierParameterList(hashMap.get(key));
            attributesArrayList.add(dehumidifierVO);
        }

        return attributesArrayList;
    }

    /**
     * 根据设备id查询楼层名字
     *
     * @param equipment
     * @return
     */
    @Nullable
    private String getaVoid(Equipment equipment) {
        List<String> objId = objMiddleMapper.findByDeviceId(equipment.getDeviceId());
        if (objId != null) {
            for (String s : objId) {
                ObjMoudel type = objMoudelMapper.findObjIdAndType(s, "1");
                if (type != null) {
                    return type.getName();
                }
            }
        }
        return null;
    }

    /**
     * 根据设备id去Redis中获取实时数据
     *
     * @param equipment
     * @return
     */
    private DehumidifierVO.DehumidifierParameter getData(Equipment equipment) {
        Map entries = redisTemplate.opsForHash().entries(equipment.getDeviceId());
        DehumidifierVO.DehumidifierParameter parameter = new DehumidifierVO.DehumidifierParameter();
        parameter.setDeviceId(equipment.getDeviceId());
        if (entries != null && entries.size() > 0) {
            //设备状态
            if (entries.containsKey("type") && entries.get("type") != null && !"".equals(entries.get("type"))) {
                parameter.setType((entries.get("type").toString()));
            }
            if (parameter.getType() != null) {
                if (parameter.getType().equals("正常")) {
                    //回风露点
                    if (entries.containsKey("returnAirDewPoint") && entries.get("returnAirDewPoint") != null && !"".equals(entries.get("returnAirDewPoint"))) {
                        parameter.setReturnAirDewPoint(Float.parseFloat(entries.get("returnAirDewPoint").toString()));
                    }
                    //回风温度
                    if (entries.containsKey("returnAirTemperature") && entries.get("returnAirTemperature") != null && !"".equals(entries.get("returnAirTemperature"))) {
                        parameter.setReturnAirTemperature(Float.parseFloat(entries.get("returnAirTemperature").toString()));
                    }
                    //送风露点
                    if (entries.containsKey("supplyAirDewPoint") && entries.get("supplyAirDewPoint") != null && !"".equals(entries.get("supplyAirDewPoint"))) {
                        parameter.setSupplyAirDewPoint(Float.parseFloat(entries.get("supplyAirDewPoint").toString()));
                    }
                    //送风温度
                    if (entries.containsKey("supplyAirTemperature") && entries.get("supplyAirTemperature") != null && !"".equals(entries.get("supplyAirTemperature"))) {
                        parameter.setSupplyAirTemperature(Float.parseFloat(entries.get("supplyAirTemperature").toString()));
                    }
                    //车间露点
                    if (entries.containsKey("roomDewPoint") && entries.get("roomDewPoint") != null && !"".equals(entries.get("roomDewPoint"))) {
                        parameter.setRoomDewPoint(Float.parseFloat(entries.get("roomDewPoint").toString()));
                    }
                    //车间温度
                    if (entries.containsKey("roomTemperature") && entries.get("roomTemperature") != null && !"".equals(entries.get("roomTemperature"))) {
                        parameter.setRoomTemperature(Float.parseFloat(entries.get("roomTemperature").toString()));
                    }
                    //MAC再生温度设定值
                    if (entries.containsKey("macregenerationTemperatureSet") && entries.get("macregenerationTemperatureSet") != null && !"".equals(entries.get("mACRegenerationTemperatureSet"))) {
                        parameter.setMacregenerationTemperatureSet(Float.parseFloat(entries.get("macregenerationTemperatureSet").toString()));
                    }
                    //MAC再生温度当前值
                    if (entries.containsKey("macregenerationTemperatureNow") && entries.get("macregenerationTemperatureNow") != null && !"".equals(entries.get("MACRegenerationTemperatureNow"))) {
                        parameter.setMacregenerationTemperatureNow(Float.parseFloat(entries.get("macregenerationTemperatureNow").toString()));
                    }
                    //LDP再生温度
                    if (entries.containsKey("ldpregenerationTemperatureNow") && entries.get("ldpregenerationTemperatureNow") != null && !"".equals(entries.get("LDPRegenerationTemperatureNow"))) {
                        parameter.setLdpregenerationTemperatureNow(Float.parseFloat(entries.get("ldpregenerationTemperatureNow").toString()));
                    }
                    //表冷温度：前冷
                    if (entries.containsKey("beforeCold") && entries.get("beforeCold") != null && !"".equals(entries.get("beforeCold"))) {
                        parameter.setBeforeCold(Float.parseFloat(entries.get("beforeCold").toString()));
                    }
                    //表冷温度：中冷冷
                    if (entries.containsKey("interCold") && entries.get("interCold") != null && !"".equals(entries.get("interCold"))) {
                        parameter.setInterCold(Float.parseFloat(entries.get("interCold").toString()));
                    }
                }
            } else {
                parameter.setType("离线");
            }

        } else {
            parameter.setType("离线");
        }
        return parameter;
    }

}
